package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@RestController
@Slf4j
public class CommonController {
    @Autowired
    private AliOssUtil aliOssUtil;

    @PostMapping("/admin/common/upload")
    public Result<String> upload(MultipartFile file) {
        try {
            // 获取上传的文件的输入流
            byte[] bytes = file.getBytes();

            // 原始文件名
            String originalFilename = file.getOriginalFilename();

            // 上传到服务器上的文件名 UUID+.jpg
            String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

            String url = aliOssUtil.upload(bytes,fileName);
            return Result.success(url);
        }catch (Exception e){
            log.info("文件{}上传失败",file);
        }
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }
}
